package com.klikmee.sms.core.base.handlers;

import java.text.MessageFormat;

import org.apache.log4j.Logger;

import com.klikmee.sms.core.base.EventManager;
import com.klikmee.sms.core.base.EventParams;
import com.klikmee.sms.core.base.dao.IncomingMessageDAO;
import com.klikmee.sms.core.base.util.Constants;
import com.klikmee.sms.core.base.util.States;
import com.klikmee.sms.core.commons.events.AppEvent;
import com.klikmee.sms.core.commons.events.EventListener;
import com.klikmee.sms.core.model.IncomingMessage;

public class OutgoingMessageEventHandlerImpl implements EventListener {

	/**
	 * Logger instance
	 */
	private Logger				logger	= Logger.getLogger( OutgoingMessageEventHandlerImpl.class );

	/**
	 * Instance of incoming message dao, used to read/write incoming messages
	 */
	private IncomingMessageDAO	incomingMessageDAO;

	@Override
	public void handleEvent(AppEvent appEvent) {
		// check for the event type
		if (appEvent.getEventType().equals( EventManager.OUTGOING_MESSAGE_ENQUEUED )) {
			onOutgoingMessageEnqueued( appEvent );
		}
	}

	/**
	 * Handler for outgoing message enqueued event. Updates the status of
	 * incomming message
	 * 
	 * @param appEvent
	 */
	private void onOutgoingMessageEnqueued(AppEvent appEvent) {
		logger.debug( MessageFormat.format( "Processing [{0}] event", appEvent.getEventType() ) );
		
		int serviceFlag = appEvent.<Integer>getData( EventParams.SERVICE_FLAG );
		IncomingMessage incomingMessage = appEvent.<IncomingMessage> getData( EventParams.INCOMING_MESSAGE );

		// update incoming message
		switch (serviceFlag) {
		case Constants.SERVICE_FLAG_BAD_SEMANTIC:
			incomingMessage.setState( States.IncommingMessage.BAD_SEMANTIC_NOTIFICATION_SENT );
			break;
		case Constants.SERVICE_FLAG_SEMANTIC_OK:
			incomingMessage.setState( States.IncommingMessage.SEMANTICALLY_OK );
			break;
		default:
			break;
		}
		this.incomingMessageDAO.edit( incomingMessage );
		logger.debug( MessageFormat.format( "Updated state of incoming message with id [{0}] to [{1}]", incomingMessage.getId(), incomingMessage.getState() ) );

	}
	
	
	public void setIncomingMessageDAO(IncomingMessageDAO incomingMessageDAO) {
		this.incomingMessageDAO = incomingMessageDAO;
	}

}
